import { useStore } from '@/hooks';
import { Button, Form, Dialog, Switch, Input, Table, Divider } from '@alifd/next';
import React, { useEffect, useState, useRef } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, FieldsGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { toJS, observable } from 'mobx';
import ChargeForm from './ChargeForm';
import ChargeDayForm from './ChargeDayForm';

const FromItem = Form.Item;

const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

const SurchargeForm = ({ modal, surchargeInfo, onCancel, onSubmit }) => {
  const { companySettingStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [surcharge] = useState(() => observable({}));
  const [state, setState] = useState([]);
  const [curCharge, setCurCharge] = useState();
  const [idx, setIdx] = useState(-1);

  const edit = modal[0] === 'edit';

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (JSON.stringify(surchargeInfo) !== '{}') {
      editCtx.origin = _.cloneDeep(surchargeInfo);
      _.assign(surcharge, surchargeInfo);
      if (surchargeInfo.itemId === '夜间行驶费' || surchargeInfo.itemId === '假日附加费') {
        const parsePrice = JSON.parse(surchargeInfo.extras.price.value);
        setState(parsePrice);
      }
    } else {
      _.set(surcharge, 'extras.selectable.title', '是否启用');
      _.set(surcharge, 'extras.selectable.value', false);
      _.set(surcharge, 'extras.price.title', '费用价格');
      _.set(surcharge, 'sortWeight', 1);
    }
  }, []);

  const timeColumns = [
    {
      title: t`序号`,
      dataIndex: 'id',
      align: 'center',
      cell: (v, i) => <span>{i + 1}</span>,
    },
    {
      title: t`时间段`,
      dataIndex: 'time',
      width: 200,
      align: 'center',
    },
    {
      title: t`费用`,
      dataIndex: 'rmb',
      width: 200,
      align: 'center',
    },
    {
      title: t`操作`,
      dataIndex: 'id',
      align: 'center',
      width: 150,
      cell: (v, i, r) => (
        <>
          <Button type="primary" text onClick={() => setCurCharge(r)}>{t`编辑`}</Button>
          <Divider direction="ver" />
          <Button type="primary" text style={{ color: 'red' }} onClick={() => handleDeleteState(i)}>{t`删除`}</Button>
        </>
      ),
    },
  ];

  const overrideModel = {
    itemId: {
      label: t`名称`,
      ui: {
        renderer: (v) => <Input value={v} readOnly={edit} placeholder="请输入费用名称" />,
        itemProps: { required: true },
      },
    },
    extras: {
      selectable: {
        value: {
          label: t`是否可选`,
          ui: {
            renderer: (v) => <Switch size="small" autoWidth checkedChildren="是" unCheckedChildren="否" checked={v} />,
          },
        },
      },
      price: {
        value: {
          label: t`费用`,
          ui: {
            renderer: (v, r) => ((r.itemId === '夜间行驶费' || r.itemId === '假日附加费') ?
              <>
                <Button type="primary" style={{ marginBottom: 10 }} onClick={handleAddState}>{t`添加时间段`}</Button>
                <Table
                  hasBorder={false}
                  dataSource={state}
                  columns={timeColumns}
                  onRowClick={(_, index) => setIdx(index)}
                />
              </>
              :
              <Input value={v} placeholder="请输入结算金额" />),
          },
        },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(surcharge, name, value);
    editCtx.changed[name] = value === _.get(editCtx.origin, name) ? undefined : value;
  };

  // 添加一个时间数据
  const handleAddState = () => {
    const { itemId } = toJS(surcharge);
    const data = {
      id: new Date().getTime(),
      time: itemId === '夜间行驶费' ? '20:00-21:00' : '10-01~10-07',
      rmb: 100,
    };
    setState([...state, data]);
  };

  // 删除一个时间数据
  const handleDeleteState = (i) => {
    setState((pre) => {
      const arr = [...pre];
      arr.splice(i, 1);
      return arr;
    });
  };

  const chargeOnSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    const { time, rmb } = values;
    const [time1, time2] = time;
    setState((pre) => {
      const newCharge = [...pre];
      const timeValue = toJS(surcharge).itemId === '夜间行驶费' ? `${time1}-${time2}` : `${time1}~${time2}`;
      newCharge[idx].time = timeValue;
      newCharge[idx].rmb = rmb;
      return newCharge;
    });
    // _.set(surcharge, 'extras.price.value', JSON.stringify(state));
    setCurCharge(false);
  };

  const handleOnCancel = () => {
    setState((pre) => {
      const newCharge = [...pre];
      newCharge[idx].time = toJS(surcharge).itemId === '夜间行驶费' ? `${newCharge[idx].time[0]}-${newCharge[idx].time[1]}` : `${newCharge[idx].time[0]}~${newCharge[idx].time[1]}`;
      return newCharge;
    });
    setCurCharge(false);
  };

  /**
   * @description 提交表单实现修改费用
   * @param {*} r formData
   */
  const handleSubmit = (__, errors) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: SurchargeForm.jsx:187 _ errors:', errors);
      return;
    }
    onSubmit?.(surcharge, state);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <>
      <TitleGrid title={t`费用信息`} />
      <Form
        inline
        value={surcharge}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <FieldsGrid
          formData={surcharge}
          mode={modal[0]}
          columns={1}
          overrideModel={overrideModel}
          fields={['itemId', 'extras.price.value', 'sortWeight', 'description', 'extras.selectable.value']}
          itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        />

        <DrawerFooter>
          <FromItem>
            <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>

        <Dialog
          visible={!!curCharge}
          onCancel={() => setCurCharge(false)}
          onClose={() => setCurCharge(false)}
          title={t`编辑费用`}
          style={{ width: '30%' }}
          footer={null}
        >
          {toJS(surcharge).itemId === '夜间行驶费' ?
            <ChargeForm
              data={curCharge}
              onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
              onCancel={() => handleOnCancel()}
            /> :
            <ChargeDayForm
              data={curCharge}
              onSubmit={(r, errors) => chargeOnSubmit(r, errors)}
              onCancel={() => handleOnCancel()}
            />
          }
        </Dialog>
      </Form>
    </>
  );
};

export default observer(SurchargeForm);
